#!/usr/bin/python
# encoding:utf-8

# ****************************************************************
# Description： 主要excel处理函数文件
# Author： Jfei
# Date：20170605
# version：
# ****************************************************************


import sys, datetime, win32com.client, re, time, os
import sendEmail
from PySerial_relase1 import SendAT
from tqdm import trange

# Excel表格中测试结果底色
PASS_COLOR = 0xffffff
FAIL_COLOR = 0xff
NT_COLOR = 0xC0C0C0

# Excel模版设置
# self.casebegin = 7      #Excel中测试用例开始行索引
# self.argbegin  = 4       #Excel中参数开始列索引

# 命令行列表

# at_list_1 ： 需要严格匹配测试结果格式的命令行
# 第一/二行：basic 命令
# 第三行：TCP/IP 命令
at_list_1 = ['AT+LSHDATE', 'AT+BDTIME?', 'AT+GSN', 'AT+CGSN', 'AT+CIMI', 'AT+COLP?', 'AT+ICCID', 'AT+HWVER',
			 'AT+LSHTEMP', 'AT^SYSINFO',
			 'AT+MIPCALL=1', 'AT+MIPCALL?', 'AT+MPING="www.baidu.com"', 'at+mipdnsr="www.baidu.com"']

# at_list_2 ： 需要模糊匹配测试结果的命令行
at_list_2 = ['AT+CGDCONT?', 'AT&V', 'AT+COPN', 'AT+TESTINF2=?', 'at+cgerep=2,1']


class create_excel:
	def read_data(self, iSheet, iRow, iCol):
		try:
			sht = self.book.Worksheets(iSheet)
			sValue = str(sht.Cells(iRow, iCol).value)

		except:
			self.close()
			print(str(iRow) + u'行' + str(iCol) + u'列读取数据失败')
			exit()

		return sValue

	def write_data(self, iSheet, iRow, iCol, sData, color = PASS_COLOR):
		try:
			sht = self.book.Worksheets(iSheet)
			sht.Cells(iRow, iCol).Value = sData
			sht.Cells(iRow, iCol).Interior.Color = color
		# self.book.Save()
		except:
			self.close()
			print(str(iRow) + u'行' + str(iCol) + u'列写入数据失败')
			exit()

	def __init__(self, sFile, suiteid, dcasebegin = 7, dargbegin = 4):
		# 定义参数个数、请求发送方法、预期结果中检查的项
		# global argsconut
		self.xlApp = win32com.client.Dispatch('Excel.Application')  # MS:Excel  WPS:et
		try:
			self.book = self.xlApp.Workbooks.Open(sFile)
		except:
			print_error_info()
			print u"打开文件失败"
			exit()
		if suiteid == 'ALL':
			self.suiteid = self.book.Worksheets(1).Name
		self.file = sFile
		self.casebegin = dcasebegin
		self.argbegin = dargbegin
		self.allresult = []
		self.caseid = 1
		self.testlevel = self.caseid + 1
		self.testcontrol = self.argbegin - 1
		self.CheckVaule = self.argbegin + 1
		self.RealCol = self.CheckVaule + 1
		self.resultCol = self.RealCol + 1
		self.resultSumCol = self.resultCol + 1
		self.TimeDelaycol = self.resultSumCol + 1
		self.attentionCol = self.TimeDelaycol + 3
		self.verrowstart = 2
		self.vercol = 2
		self.countcol = 6
		self.countpassrow = 2

	def close(self):
		# self.book.Close(SaveChanges=0)
		# self.book.Save()
		self.book.Close()
		# self.xlApp.Quit()
		del self.xlApp

	def saveAs(self):
		# type: () -> object
		# type: () -> object
		try:
			NewFilename = Timetag()
			ExcelPath = os.getcwd() + "\\TestResult\\" + NewFilename + ".xlsx"
			self.book.SaveAs(ExcelPath)
			print (u'测试结果：' + '\\TestResult\\' + NewFilename + '.xlsx' + u' 保存成功！')
		except:
			self.close()
			print_error_info()
			print (u'文件另存出错！')

	def get_all_sheetname(self):
		# 获取所有sheet页名称
		list = []
		count = self.book.Worksheets.Count
		for i in range(int(count)):
			sheetname = self.book.Worksheets(i + 1).Name
			list.append(sheetname)
		return list

	# 获取用例个数
	def get_ncase(self, iSheet):
		try:
			return self.get_nrows(iSheet) - self.casebegin + 1
		except:
			self.close()
			print(u'获取Case个数失败')
			exit()

	def get_nrows(self, iSheet):
		try:
			sht = self.book.Worksheets(iSheet)
			return sht.UsedRange.Rows.Count
		except:
			self.close()
			print(u'获取nrows失败')
			exit()

	def get_ncols(self, iSheet):
		try:
			sht = self.book.Worksheets(iSheet)
			return sht.UsedRange.Columns.Count
		except:
			self.close()
			print(u'获取ncols失败')
			exit()

	def del_testrecord(self, suiteid):
		try:
			# 获取excel中所有行数
			# print suiteid
			nrows = self.get_nrows(suiteid) + 1
			self.book.Worksheets(suiteid)

			print u'清除原始测试数据中，请等待...'

			time.sleep(0.2)
			for row in trange(nrows - self.casebegin):
				# 清除TestResul列中的测试结果
				# time.sleep(0.1)
				# 清除实际结果
				# 清除测试结果
				# 清除失败原因分析
				# 清除汇总结果列
				# 模板测试完后不保存，一直为空，不需要清空其他项目了
				# self.write_data(suiteid, row + self.casebegin, self.RealCol, ' ', PASS_COLOR)
				self.write_data(suiteid, row + self.casebegin, self.resultCol, 'NT', NT_COLOR)
			# self.write_data(suiteid, row + self.casebegin, self.attentionCol, '', PASS_COLOR)
			# self.write_data(suiteid, row + self.casebegin, self.resultSumCol, '', PASS_COLOR)

			# print ('清除原始测试数据中，请等待，当前进度 (%s:%s)   %.1f %%' %(row,nrows,(float(row)/float(nrows) *100)))
			# 在 log 界面输出进度条
			# view_bar((row - self.casebegin), (nrows - self.casebegin))
			# progressbar1(nrows - self.casebegin)

		except:
			self.close()
			print(u'清除数据失败')
			exit()

	def write_ver(self, suiteid, data):
		self.book.Worksheets(suiteid)

		for row in range(2, 5):
			self.write_data(suiteid, row, self.vercol, ' ', PASS_COLOR)
			self.write_data(suiteid, row, self.vercol, data[(row - self.verrowstart)], PASS_COLOR)

	def sum_result(self, suiteid):
		nrows = self.get_nrows(suiteid) + 1
		result = 'FAIL'
		result_list = []
		color = PASS_COLOR
		print(u'测试结果汇总处理中，请等待...')
		for row in range(nrows - self.casebegin):
			# 取出第一个case
			caseid1 = str(self.read_data(suiteid, self.casebegin + row, self.caseid))
			result1 = str(self.read_data(suiteid, self.casebegin + row, self.resultCol))
			result_list.append(result1.upper())

			caseid2 = str(self.read_data(suiteid, self.casebegin + row + 1, self.caseid))

			if caseid2.upper() != 'NONE':  # 最后一个用例后面没有用例，特殊处理，前面所有用例都走
				caseid1, caseid2 = caseid1.split('.'), caseid2.split('.')
				caseid1_bit3, caseid2_bit3 = caseid1[2], caseid2[2]  # 取出测试用例ID第3位
				caseid1_bit4, caseid2_bit4 = caseid1[3], caseid2[3]  # 取出测试用例ID第4位

				if (caseid1_bit4 != caseid2_bit4) or (caseid1_bit3 != caseid2_bit3):
					for result in result_list:
						if result == 'FAIL':
							color = FAIL_COLOR
							break
						elif result == 'NT':
							color = NT_COLOR
							break
						else:
							color = PASS_COLOR
					self.write_data(suiteid, self.casebegin + row, self.resultSumCol, result, color)

					result_list = []
			else:  # 如果caseid取出为None，说明已经结束，直接处理用例结果
				for result in result_list:
					if result == 'FAIL':
						color = FAIL_COLOR
						break
					elif result == 'NT':
						color = NT_COLOR
						break
					else:
						color = PASS_COLOR
				self.write_data(suiteid, self.casebegin + row, self.resultSumCol, result, color)

				result_list = []


def process_result(sReal, sExpect, sendat):
	"""
	结果处理函数
	:param sReal: AT命令返回结果
	:param sExpect: AT命令期望返回结果
	:param sendat: 本次测试的命令行
	:return:
	"""
	result = "FAIL"
	# print sendat

	# 期望结果为空或者实际结果空直接返回fail
	if "None" == sExpect or "None" == sReal:
		return result

	at_list_1_upper = [item.upper() for item in at_list_1]
	at_list_2_upper = [item.upper() for item in at_list_2]

	# 测试命令行需要严格匹配格式的命令行处理
	if sendat.upper() in at_list_1_upper:
		sReal = re.sub(r'[\n\t\r ]', '', sReal)
		# print "1"
		if 'AT+MIPCALL=1'.upper() == sendat.upper():  # AT+MIPCALL=1 命令行处理
			ret = re.match(
				r'AT\+MIPCALL=1\+MIPCALL:\d,'
				r'(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])'
				r'\+MIP:OKOK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+MIPCALL?'.upper() == sendat.upper():  # AT+MIPCALL? 命令行处理
			ret = re.match(
				r'AT[+]MIPCALL[?][+]MIPCALL:\d,'
				r'(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])'
				r'OK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+MPING="www.baidu.com"'.upper() == sendat.upper():  # AT+MPING="www.baidu.com" 命令行处理
			ret = re.match(
				r'AT\+MPING="www\.baidu\.com"OK'
				r'(\+MPING:(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5]),\d,\d+){4}'
				r'\+MPINGSTATE:(\d,){3}\d+'
				r'OK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'at+mipdnsr="www.baidu.com"'.upper() == sendat.upper():  # at+mipdnsr="www.baidu.com" 命令行处理
			ret = re.match(
				r'at\+mipdnsr="www\.baidu\.com"\+MIPDNSR:'
				r'(?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d?\d|2[0-4]\d|25[0-5])'
				r'\+MIP:OK'
				r'OK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+LSHDATE'.upper() == sendat.upper():  # AT+LSHDATE 命令行处理,时间使用精确
			"""
			正则年份匹配规则说明：
			1.匹配除了2月份之外的1-30日
			2.若1无法匹配，则匹配1，3，5，7，8，10，12月份的31日
			3.若2无法匹配，则匹配2月份的1-28日
			"""
			ret = re.match(
				r'AT\+LSHDATE'
				r'\+LSHDATE:^((((19|20)\d{2})(0?[13-9]|1[012])(0?[1-9]|[12]\d|30))|(((19|20)\d{2})(0?[13578]|1['
				r'02])31)|(((19|20)\d{2})0?2(0?[1-9]|1\d|2[0-8]))|((((19|20)([13579][26]|[2468][048]|0[48]))|('
				r'2000))0?229))$'
				r'OK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+BDTIME?'.upper() == sendat.upper():  # AT+BDTIME? 命令行处理,时间使用精确
			"""
			正则年份匹配规则说明：
			一月：January 简写Jan. 
			二月：February 简写Feb. 
			三月：March 简写Mar. 
			四月：April 简写Apr. 
			五月：May 简写May. 
			六月：June 简写Jun. 
			七月：July 简写Jul. 
			八月：August 简写Aug. 
			九月：September 简写Sep. / Sept. 
			十月：October 简写Oct. 
			十一月：November 简写Nov. 
			十二月：December 简写Dec.
			
			1.匹配除了2月份之外的1-30日
			2.若1无法匹配，则匹配1，3，5，7，8，10，12月份的31日
			3.若2无法匹配，则匹配2月份的1-28日
			
			AT+BDTIME?
			data:Jul  5 2017 time 18:17:11
			OK
			"""
			ret = re.match(
				r'AT\+BDTIME\?data:'
				r'(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Sept|Oct|Nov|Dec)(\d|\d\d)(19|20)\d{2}'
				r'time(\d{2}:){2}(\d{2})'
				r'OK',
				sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+GSN' == sendat.upper() or \
						'AT+CGSN' == sendat.upper() or \
						'AT+CIMI'== sendat.upper():  # AT+GSN/CGSN /AT+CIMI命令行处理
			"""
			AT+GSN
			862104024206291
			OK
			"""
			ret = re.match(r'AT\+GSN\d{15}OK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+COLP?'.upper() == sendat.upper():  # AT+COLP? 命令行处理
			"""
			AT+COLP?
			+COLP: 0,2
			OK
			"""
			ret = re.match(r'AT\+COLP\?\+COLP:\d,\dOK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+ICCID'.upper() == sendat.upper():  # AT+ICCID 命令行处理
			"""
			at+iccid
			^SCID: 89860116884032703562
			OK
			"""
			ret = re.match(r'at\+iccid\^SCID:\d{20}OK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+HWVER'.upper() == sendat.upper():  # AT+HWVER 命令行处理
			"""
			AT+HWVER
			1011
			OK
			"""
			ret = re.match(r'AT\+HWVER\d{4}OK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+LSHTEMP'.upper() == sendat.upper():  # AT+LSHTEMP 命令行处理
			"""
			AT+LSHTEMP
			+LSHTEMP: 29
			OK
			匹配 0-99 度，其他温度返回fail
			"""
			ret = re.match(r'AT\+LSHTEMP\+LSHTEMP:\d{1,2}OK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT^SYSINFO'.upper() == sendat.upper():  # AT^SYSINFO 命令行处理
			"""
			AT^SYSINFO
			^SYSINFO:2,3,0,2,1
			OK
			"""
			ret = re.match(r'AT\^SYSINFO\^SYSINFO:(\d,){4}\dOK', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

	# 测试结果需要模糊匹配格式
	elif sendat.upper() in at_list_2_upper:
		# print "2"
		# 处理期望结果和实际结果中的AT命令字段
		sReal = re.sub(r'[\n\t\r ]', '', sReal)
		if 'AT+COPN'.upper() == sendat.upper():  # AT+COPN 命令行处理
			"""
			AT+COPN
			+COPN:
			……
			OK
			"""
			ret = re.match(r'AT\+COPN\+COPN:.+OK$', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+CGDCONT?'.upper() == sendat.upper():  # AT+CGDCONT? 命令行处理
			"""
			AT+CGDCONT?
			+CGDCONT: 1,"IPV4V6","CMNET","0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0",0,0,0,0
			+CGDCONT: 2,"IP","CMNET","0.0.0.0",0,0,0,0
			+CGDCONT: 3,"IPV4V6","WONET","0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0",0,0,0,0
			+CGDCONT: 23,"IP","CMNET","0.0.0.0",0,0,0,0
			+CGDCONT: 24,"IP","CMNET","0.0.0.0",0,0,0,0
			OK
			"""
			ret = re.match(r'AT\+CGDCONT\?\+CGDCONT:\d+,"IP.+OK$', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'AT+TESTINF2=?'.upper() == sendat.upper():  # AT+TESTINF2=? 命令行处理
			"""
			AT+TESTINF2=?
			+TESTINF2:"MMI:1,SN:1,IMEI:1,MEID:1,BT:1,LTEF:1,TDS:1,W:1,GPS:1"
			OK
			"""
			ret = re.match(r'AT\+TESTINF2=\?\+TESTINF2:".+OK$', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		elif 'at+cgerep=2,1'.upper() == sendat.upper():  # at+cgerep=2,1 命令行处理
			"""
			at+cgerep=2,1
			OK
			+CGEV: ME DETACH
			……
			+CGEV: ME DETACH
			+CGEV: NW DETACH
			……
			+CGEV: ME DETACH
			该命令行会缓存之前所有的gprs附着和断开的相关信息，无法预知返回结果
			"""
			ret = re.match(r'at\+cgerep=2,1OK(\+CGEV:(NW|ME)DETACH)+', sReal, re.I)
			if ret:
				result = "PASS"
			else:
				result = "FAIL"

		else:  # 目前仅有 AT&V 使用该分支
			ret_at = sReal.find(sendat)

			# 如果找到AT则删除AT命令行之前的所有字符
			if ret_at != -1:
				sReal = sReal[(ret_at + len(sendat)):]
				ret = re.match(r'.+OK$', sReal)
				if ret:
					result = "PASS"
				else:
					result = "FAIL"

	# 测试结果需要精确匹配相等
	else:
		# print "3"
		# 对期望结果和实际返回值进行处理
		sReal = assert_AT(sendat, sReal)
		sExpect = assert_AT(sendat, sExpect)

		if sReal == sExpect:
			result = 'PASS'
		else:
			result = 'FAIL'

	return result


def assert_AT(sendat, result):
	if sendat is None or result is None:
		return None

	# 需要匹配的结果进行预处理
	sendat = (sendat.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')).upper()
	result = (result.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')).upper()

	# 处理期望结果和实际结果中的AT命令字段
	ret_at = result.find(sendat)
	# print ret_at , 'ret_at'

	# 如果找到AT则删除AT命令行之前的所有字符
	if ret_at != -1:
		result = result[(ret_at + len(sendat)):]
	return result


# 结果判断,作废暂不使用，代码保留
def assert_result(sReal, sExpect):
	# 预期结果和实际结果都是空的情况需要特别处理下

	sReal = (sReal.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')).upper()
	# print 'Test Rusult:\n',sReal
	# print len(sReal)
	sExpect = (sExpect.replace(' ', '').replace('\n', '').replace('\t', '').replace('\r', '')).upper()
	# print 'Test Rusult:\n',sExpect
	# print len(sExpect)

	if sReal == sExpect:
		return 'PASS'
	else:
		return 'FAIL'


# 将测试结果写入文件
def write_result(Data, SuiteId, CaseId, resultcol, result):
	if result == 'FAIL':
		Data.write_data(SuiteId, Data.casebegin + CaseId, resultcol, result, FAIL_COLOR)
	elif result == 'PASS':
		Data.write_data(SuiteId, Data.casebegin + CaseId, resultcol, result, PASS_COLOR)
	else:  # NT
		Data.write_data(SuiteId, Data.casebegin + CaseId, resultcol, result, NT_COLOR)
	# Data.allresult.append(result)

	# 将当前结果立即打印
	# print 'case' + str(CaseId + 1) + ':', Data.allresult[-1]
	print 'case' + str(CaseId + 1) + ':', result


# 打印测试结果
def statisticresult(excelobj):
	allresultlist = excelobj.allresult
	# print allresultlist
	count = [0, 0, 0]
	for i in range(0, len(allresultlist)):
		# print 'case'+str(i+1)+':', allresultlist[i]
		count = countflag(allresultlist[i], count[0], count[1], count[2])
	print '测试结果:'
	print 'PASS     :    ', count[0]
	print 'FAIL     :    ', count[1]
	print 'NT       :    ', count[2]
	return count


def statisticresult2(excelobj, SuiteId):
	count = []
	for i in range(0, 3):
		try:
			ret = float(excelobj.read_data(SuiteId, excelobj.countpassrow + i, excelobj.countcol))
			count.append(int(ret))
		except:
			print_error_info()
			print (u'读取测试结果出错！')
	print u'测试结果:'
	print 'PASS     :    ', count[0]
	print 'FAIL     :    ', count[1]
	print 'NT       :    ', count[2]
	return count


# 去除历史数据expect[real]
def delcomment(excelobj, suiteid, iRow, iCol, str):
	startpos = str.find('[')
	if startpos > 0:
		str = str[0:startpos].strip()
		excelobj.write_data(suiteid, iRow, iCol, str, PASS_COLOR)
	return str


def clearcount(excelobj):
	excelobj.allresult = []
	return excelobj.allresult


# 检查每个item （非结构体）
def check_result(excelobj, suiteid, caseid, real_value, checkcol):
	ret = 'PASS'
	excelobj.write_data(suiteid, excelobj.casebegin + caseid, 16, 'PASS', PASS_COLOR)
	# real=real_value[checklist[checkid]]['value']
	real = real_value
	expect = excelobj.read_data(suiteid, excelobj.casebegin + caseid, checkcol)

	# 如果检查不一致测将实际结果写入expect字段，格式：expect[real]
	# 将return FAil
	result = assert_result(real, expect)

	if result == 'FAIL':

		writestr = real
		if writestr == None:
			writestr = u"预期结果的value值为空！"
			excelobj.write_data(suiteid, excelobj.casebegin + caseid, 15, writestr, FAIL_COLOR)
			excelobj.write_data(suiteid, excelobj.casebegin + caseid, 16, 'FAIL', FAIL_COLOR)
			ret = 'FAIL'
		else:
			excelobj.write_data(suiteid, excelobj.casebegin + caseid, 15, writestr, FAIL_COLOR)
			excelobj.write_data(suiteid, excelobj.casebegin + caseid, 16, 'FAIL', FAIL_COLOR)
			ret = 'FAIL'

	return ret


# 获取异常函数及行号
def print_error_info():
	"""Return the frame object for the caller's stack frame."""
	try:
		raise Exception
	except:
		f = sys.exc_info()[2].tb_frame.f_back
	print (f.f_code.co_name, f.f_lineno)


# 测试结果计数器，类似Switch语句实现
def countflag(flag, PASS, FAIL, NT):
	calculation = {'PASS': lambda: [PASS + 1, FAIL, NT],
				   'FAIL': lambda: [PASS, FAIL + 1, NT],
				   'NT': lambda: [PASS, FAIL, NT + 1]}
	return calculation[flag]()


def getversion(comid):
	cmd = 'AT+LCTSW'
	ret = SendAT(comid, cmd, 0.5)
	ret = ret.splitlines()  # 转成列表处理
	ret = ret[2:5]  # 拆掉无用的头尾信息
	return ret


def versionOut(ver):
	try:
		print '*' * 70
		# print ver
		print u'当前测试版本号 ：'
		print u'版本号1	：		', ver[0]
		print u'版本号2	：		', ver[1]
		print u'版本号3	：		', ver[2]
		print '*' * 70
	except:
		print(u'---版本获取失败---')
		exit()


def ver_excel():
	pass


# def Sendmail (maillist, bodycontent, count, interfacename):
def Sendmail(maillist, count, interfacename):
	strHtml = ''
	interfacename = str(interfacename)
	strHtml += '<B><p style="font-size:16px">' + interfacename + '测试结果:</p></B>'
	strHtml += '<B><p style="font-size:14px">' + 'Statistic result as follow:</p></B>'
	strHtml += '<B><p style="font-size:14px">' + 'PASS  :\t' + str(count[0]) + '</p></B>'
	strHtml += '<B><p style="font-size:14px">' + 'FAIL  :\t' + str(count[1]) + '</p></B>'
	strHtml += '<B><p style="font-size:14px">' + 'NT    :\t' + str(count[2]) + '</p></B>'
	strHtml += '<table width="1000" border="1">'
	strHtml += '<tr>'

	# for i in range(len(bodycontent)):
	# 	content = ''.join(bodycontent[i])
	# 	content = str(content)
	# 	# print type(content)
	# 	if i == 0:
	# 		strHtml += '<tr>'
	# 	strHtml += '<td>' + content + '</td>'
	# 	if (i + 1) % 4 == 0:
	# 		strHtml += '</tr><tr>'
	# strHtml = strHtml[:-4]
	# strHtml += '</table>'

	mail_from = 'jiangfei@longsung.com'
	mail_to = maillist
	timenow = datetime.datetime.utcnow() + datetime.timedelta(hours = 8)  # 东8区增加8小时
	title = '【' + interfacename + '_测试结果】    ' + timenow.strftime('%Y-%m-%d %H:%M:%S')
	body = strHtml
	if count[1] == 0:
		print 'All Case is PASS!'
	sendEmail.SendMail(mail_from, mail_to, title, body)


# 进度条函数，在log输入模拟进度条
def view_bar(num, total):
	# print num,total
	rate = (float(num + 1) / float(total))
	# print rate
	rate_num = int(rate * 100)
	# print rate_num
	r = '\r[%s%s] %.1f %%' % ("=" * rate_num, " " * (100 - rate_num), rate * 100)
	if (total < 101) or ((num % 5 == 0)) or ((num + 1) == total):
		sys.stdout.write(r)
		time.sleep(0.3)
		sys.stdout.flush()


def progressbar1(i, count):
	view_bar(i, count)


def progressbar2(count):
	trange(count)
	time.sleep(0.3)


def Timetag():  # 记录执行时间
	return time.strftime("%Y%m%d_%H%M%S", time.localtime())


if __name__ == "__main__":
	print Timetag()
